const jwt = require("jsonwebtoken");

module.exports = () => {
    return async function auth(ctx, next) {
        let { authorization } = ctx.request.headers;
        // 判断token 是否有值 有值说明用户登录过
        if (authorization) {
            const token = authorization.split("Bearer ")[1];
            try {
                jwt.verify(token, "sx");
                try {
                    await next();
                } catch (error) {
                    ctx.body = error;
                }
            } catch (error) {
                ctx.body = {
                    code: "200",
                    msg: "登录异常，请重新登录",
                };
            }
        } else {
            // 没有值 用户没登录过
            ctx.body = {
                code: "200",
                msg: "您还未登录,请先登录",
            };
        }
    };
};